using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core;
using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml;
using AvaloniaUI.Modal;
using AvaloniaUI.Modal.Controls;
using AvaloniaUI.Modal.Demo.ViewModels;
using AvaloniaUI.Modal.Demo.Views;
using AvaloniaUI.Modal.Services;

namespace AvaloniaUI.Modal.Demo;

public partial class App : Application
{
    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
        this.UseModal(); // 添加模态对话框支持
    }

    public override void OnFrameworkInitializationCompleted()
    {
        if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
        {
            // Line below is needed to remove Avalonia data validation.
            // Without this line you will get duplicate validations from both Avalonia and CT
            BindingPlugins.DataValidators.RemoveAt(0);
            desktop.MainWindow = new MainWindow
            {
                DataContext = new MainWindowViewModel(),
            };
            
            // 初始化ModalHost
            InitializeModalHost(desktop.MainWindow);
        }
        // 注意：此Demo项目是桌面应用程序，不需要处理ISingleViewApplicationLifetime
        // 在实际项目中，如果需要支持单视图应用程序，可以添加类似以下代码：
        /*
        else if (ApplicationLifetime is ISingleViewApplicationLifetime singleView)
        {
            // 单视图应用程序（如移动应用）
            var mainView = new Control(); // 使用适当的视图类型
            singleView.MainView = mainView;
            
            // 为单视图应用初始化ModalHost
            ModalService.Instance.CreateModalHostForView(mainView, true);
        }
        */
        
        base.OnFrameworkInitializationCompleted();
    }
    
    /// <summary>
    /// 为窗口初始化ModalHost
    /// </summary>
    /// <param name="window">目标窗口</param>
    private void InitializeModalHost(Window window)
    {
        if (window == null)
            return;
            
        // 获取窗口的根面板
        var rootPanel = window.Content as Panel;
        if (rootPanel == null)
        {
            // 如果窗口的内容不是Panel，则创建一个新的Grid
            var originalContent = window.Content;
            rootPanel = new Grid();
            window.Content = rootPanel;
            
            if (originalContent != null && originalContent is Control control)
            {
                rootPanel.Children.Add(control);
            }
        }
        
        //// 创建并添加ModalHost
        //var modalHost = new ModalHost { IsDefault = true };
        //rootPanel.Children.Add(modalHost);
    }
    
}